<!--  -->
<template>
  <div>
    <el-button type="primary"  @click="dialogFormVisible = true" >新增</el-button>
    <el-button type="primary"  @click="exportex()" >导出</el-button>
  <el-table @row-dblclick="userrowDBclick" :data="tableData.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))" stripe style="width: 100%"  height="800">
    <el-table-column prop="loginname" label="登录名" width="210" align="center"></el-table-column>
    <el-table-column prop="username" label="姓名" width="210"  align="center"></el-table-column>
    <el-table-column prop="phone" label="手机" width="210"  align="center"></el-table-column>
    <el-table-column prop="partname" label="部门" width="210"  align="center"></el-table-column>
    <el-table-column align="right">
      <template slot="header" slot-scope="scope">
        <el-input
          v-model="search"
          size="mini"
          placeholder="输入关键字搜索"/>
      </template>
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog title="新建用户" :visible.sync="dialogFormVisible">
  <el-form :model="form" :rules="rules">
    <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
      <el-input v-model="form.username" autocomplete="off" placeholder="用户名只能2-4个汉字"></el-input>
    </el-form-item>
     <el-form-item label="登录名" :label-width="formLabelWidth" prop="loginname">
      <el-input v-model="form.loginname" autocomplete="off" placeholder="4到16位（字母，数字，下划线，减号）"></el-input>
    </el-form-item>
     <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
      <el-input v-model="form.password" autocomplete="off" type="password" placeholder="6到16位（字母，数字，下划线，减号）"></el-input>
    </el-form-item>
    <el-form-item label="手机" :label-width="formLabelWidth" prop="phone">
      <el-input v-model="form.phone" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="选择头像" :label-width="formLabelWidth">
      <!-- <el-input v-model="form.icon" type="file"></el-input> action="doUpload" -->
      <el-upload
      class="upload-demo"
      ref="upload"
      :limit="1"
      action=""
      :before-upload="beforeUpload">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
      <div slot="tip" class="el-upload__tip">只能上传png、jpg、jpeg文件，且不超过1MB</div>
      <div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
      </el-upload> 
    </el-form-item>
</el-upload>
    
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitUpload()">创 建</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      search: '',
      tableData: [],
      dialogFormVisible: false,
      form:{
        username:'',
        loginname:'',
        password:'',
        phone:''
      },
      fileName:'',
      formLabelWidth: '120px',
      rules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            validator:function(rule, value, callback){
              //用户名正则，4到16位（字母，数字，下划线，减号 汉字）
              var uPattern = /^[\u4e00-\u9fa5]{2,4}$/;
              if(!uPattern.test(value)){
                 callback(new Error('登录名格式不正确！'))
              }else{
                 callback()
              }
            },
            trigger: 'blur'
          }
        ],
        loginname:[
          { required: true, message: '请输入登录名', trigger: 'blur' },
          {
            validator:function(rule, value, callback){
              //用户名正则，4到16位（字母，数字，下划线，减号）
              var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
              if(!uPattern.test(value)){
                 callback(new Error('登录名格式不正确！'))
              }else{
                 callback()
              }
            },
            trigger: 'blur'
          }
        ],
        password:[
          {required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator:function(rule, value, callback){
              //用户名正则，4到16位（字母，数字，下划线，减号）
              var uPattern = /^[a-zA-Z0-9_-]{6,16}$/;
              if(!uPattern.test(value)){
                 callback(new Error('密码格式不正确！'))
              }else{
                 callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              var MobileRegex = /^(13[0-9]|147|15[0-9]|17[0-9]|18[0-9])\d{8}$/
              if (!MobileRegex.test(value)) {
                callback(new Error('手机号码格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    async exportex(){
       //await this.$axios.get("/user/exportex").
        this.$axios.post('/user/exportex',{headers: {
                'Content-Type': 'application/json; application/octet-stream'
            },responseType: 'arraybuffer'}).
        then(response => {
            //console.log(Object.prototype.toString.call(response.data.data))
            let uint8= new Uint8Array(response.data.data);//变成uint8 
            //变成buffer
            let buffer=uint8.buffer;
            let url = window.URL.createObjectURL(new Blob([buffer], {type: 'application/vnd.ms-excel;charset=utf-8'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            //link.setAttribute('download', 'excel.xlsx')
            document.body.appendChild(link)
            link.click()
          }).catch((error) => {
          console.log(error);
          })
    },
    userrowDBclick(row, event){
        //console.log(row,event);
        this.$router.push({path:'/usercalendar',query:{loginname:row.loginname,username:row.username}})
    },
     handleEdit(index, row) {
        console.log(index, row);
      },
      handleDelete(index, row) {
        console.log(index, row);
      },
    async getuserlist() {
      let { data } = await this.$axios.get("/user/getalluser");
      this.tableData=data;
    },
    async adduser(){
      await this.$axios.post("/user/adduser")
    },
    beforeUpload(file){
      this.files = file;
      const extension = file.name.split('.')[1] === 'jpg'
      const extension2 = file.name.split('.')[1] === 'png'
      const extension3 = file.name.split('.')[1] === 'jpeg'
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!extension && !extension2&& !extension3) {
        this.$message.warning('上传模板只能是 png、jpg、jpeg格式!')
        return
      }
      if (!isLt2M) {
        this.$message.warning('上传模板大小不能超过 1MB!')
        return
      }
      this.fileName = file.name;
        return false // 返回false不会自动上传
    },
    submitUpload() {
      //console.log('上传'+this.files.name)
      if(this.fileName == ""){
        this.$message.warning('请选择要上传的文件！')
        return false
      }
      let fileFormData = new FormData();
        fileFormData.append('username',this.form.username);
        fileFormData.append('loginname',this.form.loginname);
        fileFormData.append('password',this.form.password);
        fileFormData.append('phone',this.form.phone);
        fileFormData.append('file', this.files, this.fileName);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      let requestConfig = {
        headers: {
        'Content-Type': 'multipart/form-data'
        },
      }
      
       this.$axios.post('/user/adduser', fileFormData, requestConfig).then((data) => {
        if (data && data.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
            this.dialogFormVisible = false
            this.getuserlist();
            }
        })
        } else {
        this.$message.error(data.msg)
        }
      }) 
    }
  },

  created() {
    this.getuserlist();
  }
};
</script>
<style  lang='less'  scoped>
</style>